<template>
  <div class="forum-container">
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" size="large" class="action-button" @click="showPostDialog">
        <i class="el-icon-edit"></i> 发布帖子
      </el-button>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索帖子"
        clearable
        prefix-icon="el-icon-search"
        style="width:300px; margin-left:20px"
      />
    </div>

    <!-- 帖子列表 -->
    <div class="post-list">
      <el-card
        v-for="post in displayedPosts"
        :key="post.post_id"
        class="post-card"
        shadow="hover"
      >
        <template #header>
          <div class="post-header">
            <span class="post-title">{{ post.title }}</span>
            <div class="post-actions" v-if="post.user_id == auth.userId">
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="deletePost(post.post_id)"
              />
            </div>
          </div>
        </template>
        <div class="post-content">
          <p>{{ post.content }}</p>
          <p class="post-meta">
            发布者: {{ post.username || post.user_id }} 发布于: {{ formatDate(post.post_time) }}
          </p>
          <!-- 点赞/点踩/回复 -->
          <div class="vote-actions">
            <el-button type="text" @click="upvotePost(post.post_id)">
              <i class="el-icon-thumb"></i> 赞 {{ post.upvotes }}
            </el-button>
            
            <el-button type="text" @click="downvotePost(post.post_id)">
              <i class="el-icon-thumb-down"></i> 踩 {{ post.downvotes }}
            </el-button>
            <el-button type="text" @click="showReplyDialog(post.post_id)">回复</el-button>
            <el-button type="text" @click="viewPost(post)">查看</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 发布帖子弹窗 -->
    <el-dialog :title="newPost.parent_post_id ? '回复帖子' : '发布新帖子'" v-model="dialogVisible" width="50%">
      <el-form :model="newPost" label-width="100px">
        <el-form-item v-if="!newPost.parent_post_id" label="标题" required>
          <el-input v-model="newPost.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" required>
          <el-input
            type="textarea"
            rows="4"
            v-model="newPost.content"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPost" :loading="loading">
          {{ newPost.parent_post_id ? '回复' : '发布' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 帖子详情弹窗 -->
    <el-dialog title="帖子详情" v-model="viewDialogVisible" width="60%">
      <div v-if="currentViewPost">
        <div ref="chartRef" style="width:100%;height:300px;"></div>
        <div class="replies-list" style="margin-top:20px;">
          <el-card
            v-for="reply in currentReplies"
            :key="reply.post_id"
            class="reply-card"
            shadow="hover"
            style="margin-bottom:10px"
          >
            <div class="post-content">
              <p>{{ reply.content }}</p>
              <p class="post-meta">回复者: {{ reply.username || reply.user_id }} 发布于: {{ formatDate(reply.post_time) }}</p>
            </div>
          </el-card>
        </div>
      </div>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue'
import { useAuthStore } from '../store/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'

const auth = useAuthStore()
const posts = ref([])
const userMap = ref(new Map())
// 只显示顶级帖子
const topLevelPosts = computed(() => posts.value.filter(p => !p.parent_post_id))
const loading = ref(false)
const dialogVisible = ref(false)
// 记录新帖/回复，包含 parent_post_id
const newPost = ref({ title: '', content: '', parent_post_id: null })
// 获取指定帖子的回复列表
const getReplies = (parentId) => posts.value.filter(p => p.parent_post_id === parentId)
// 搜索关键词
const searchKeyword = ref('')
// 根据搜索关键词过滤帖子
const displayedPosts = computed(() => {
  const key = searchKeyword.value.trim().toLowerCase()
  if (!key) return topLevelPosts.value
  return topLevelPosts.value.filter(post =>
    post.title.toLowerCase().includes(key) ||
    post.content.toLowerCase().includes(key)
  )
})

// 查看详情弹窗
const viewDialogVisible = ref(false)
const currentViewPost = ref(null)
const chartRef = ref(null)

// 获取用户信息
const fetchUserInfo = async (userId) => {
  if (userMap.value.has(userId)) {
    return userMap.value.get(userId)
  }
  try {
    const token = auth.token || localStorage.getItem('token')
    const res = await fetch(`http://127.0.0.1:8000/api/users/${userId}`, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${encodeURIComponent(token)}`
      }
    })
    if (!res.ok) throw new Error(await res.text())
    const user = await res.json()
    userMap.value.set(userId, user.username)
    return user.username
  } catch (err) {
    console.error('获取用户信息失败:', err)
    return userId
  }
}

// 获取帖子列表
const fetchPosts = async () => {
  loading.value = true
  try {
    const token = auth.token || localStorage.getItem('token')
    const res = await fetch('http://127.0.0.1:8000/api/forum-posts', {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${encodeURIComponent(token)}`
      }
    })
    if (!res.ok) throw new Error(await res.text())
    const postsData = await res.json()
    
    // 获取所有帖子的用户信息
    const uniqueUserIds = new Set(postsData.map(post => post.user_id))
    const userPromises = Array.from(uniqueUserIds).map(userId => fetchUserInfo(userId))
    await Promise.all(userPromises)
    
    // 将用户名添加到帖子数据中
    posts.value = postsData.map(post => ({
      ...post,
      username: userMap.value.get(post.user_id) || post.user_id
    }))
  } catch (err) {
    ElMessage.error('获取帖子失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dt) => {
  if (!dt) return ''
  return new Date(dt).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 显示发帖弹窗
const showPostDialog = () => {
  newPost.value = { title: '', content: '', parent_post_id: null }
  dialogVisible.value = true
}

// 显示回复弹窗
const showReplyDialog = (parentId) => {
  const parentPost = posts.value.find(p => p.post_id === parentId)
  newPost.value = { 
    title: `回复: ${parentPost?.title || ''}`, 
    content: '', 
    parent_post_id: parentId 
  }
  dialogVisible.value = true
}

// 查看帖子详情
const viewPost = async (post) => {
  currentViewPost.value = post
  // 确保当前帖子的用户信息已加载
  if (!userMap.value.has(post.user_id)) {
    await fetchUserInfo(post.user_id)
  }
  viewDialogVisible.value = true
}

// 当前查看帖子的回复列表
const currentReplies = computed(() => {
  return currentViewPost.value ? getReplies(currentViewPost.value.post_id) : []
})

// 初始化图表
watch(() => viewDialogVisible.value, (visible) => {
  if (visible && currentViewPost.value) {
    nextTick(() => {
      const chartDom = chartRef.value
      const myChart = echarts.init(chartDom)
      const option = {
        title: { text: '点赞/点踩统计' },
        tooltip: {},
        legend: { data: ['数量'] },
        xAxis: { data: ['点赞','点踩'] },
        yAxis: {},
        series: [{ name: '数量', type: 'bar', data: [currentViewPost.value.upvotes, currentViewPost.value.downvotes] }]
      }
      myChart.setOption(option)
    })
  }
})

// 提交新帖子
const submitPost = async () => {
  loading.value = true
  try {
    if (!newPost.value.content) {
      ElMessage.warning('请填写内容')
      return
    }
    if (!newPost.value.parent_post_id && !newPost.value.title) {
      ElMessage.warning('请填写标题')
      return
    }
    const token = auth.token || localStorage.getItem('token')
    const userId = auth.userId
    const res = await fetch('http://127.0.0.1:8000/api/forum-posts', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${encodeURIComponent(token)}`
      },
      body: JSON.stringify({ 
        ...newPost.value, 
        user_id: parseInt(userId),
        title: newPost.value.parent_post_id ? `回复: ${posts.value.find(p => p.post_id === newPost.value.parent_post_id)?.title || ''}` : newPost.value.title
      })
    })
    if (!res.ok) throw new Error(await res.text())
    ElMessage.success(newPost.value.parent_post_id ? '回复成功' : '发布成功')
    dialogVisible.value = false
    fetchPosts()
  } catch (err) {
    ElMessage.error((newPost.value.parent_post_id ? '回复' : '发布') + '失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

// 删除帖子
const deletePost = async (postId) => {
  try {
    await ElMessageBox.confirm('确定删除该帖子？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    loading.value = true
    const token = auth.token || localStorage.getItem('token')
    const userId = auth.userId
    const res = await fetch(
      `http://127.0.0.1:8000/api/forum-posts/${postId}?user_id=${userId}`,
      {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${encodeURIComponent(token)}`
        }
      }
    )
    if (!res.ok) throw new Error(await res.text())
    ElMessage.success('删除成功')
    fetchPosts()
  } catch (err) {
    if (err !== 'cancel') ElMessage.error('删除失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

// 点赞帖子
const upvotePost = async (postId) => {
  try {
    const token = auth.token || localStorage.getItem('token')
    const res = await fetch(
      `http://127.0.0.1:8000/api/forum-posts/${postId}/upvote`,
      { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${encodeURIComponent(token)}` } }
    )
    if (!res.ok) throw new Error(await res.text())
    fetchPosts()
  } catch (err) {
    ElMessage.error('点赞失败: ' + err.message)
  }
}

// 点踩帖子
const downvotePost = async (postId) => {
  try {
    const token = auth.token || localStorage.getItem('token')
    const res = await fetch(
      `http://127.0.0.1:8000/api/forum-posts/${postId}/downvote`,
      { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${encodeURIComponent(token)}` } }
    )
    if (!res.ok) throw new Error(await res.text())
    fetchPosts()
  } catch (err) {
    ElMessage.error('点踩失败: ' + err.message)
  }
}

onMounted(fetchPosts)
</script>

<style scoped>
.forum-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  min-height: 100vh;

}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-button {
  padding: 10px 20px;
  font-size: 16px;
  background: linear-gradient(45deg, #409EFF, #36cfcf);
  border: none;
  transition: all 0.3s;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.post-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.post-card {
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.95);
  transition: all 0.3s;
  border: none;
}

.post-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.post-title {
  font-weight: bold;
  font-size: 18px;
  color: #409EFF;
  background: linear-gradient(45deg, #409EFF, #36cfcf);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.post-content {
  padding: 15px;
  font-size: 14px;
  line-height: 1.6;
}

.post-meta {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.dialog-footer {
  text-align: right;
}

.vote-actions {
  display: flex;
  gap: 15px;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.vote-actions .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #606266;
  transition: all 0.3s;
}

.vote-actions .el-button:hover {
  color: #409EFF;
  transform: scale(1.05);
}

.vote-actions i {
  font-size: 16px;
}

/* 弹窗样式 */
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background: linear-gradient(45deg, #409EFF, #36cfcf);
  margin: 0;
  padding: 15px 20px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: bold;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
}

/* 回复卡片样式 */
.reply-card {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  margin-bottom: 15px;
  transition: all 0.3s;
}

.reply-card:hover {
  transform: translateX(5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 搜索框样式 */
:deep(.el-input__inner) {
  border-radius: 20px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

:deep(.el-input__inner:focus) {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 按钮样式 */
:deep(.el-button--primary) {
  background: linear-gradient(45deg, #409EFF, #36cfcf);
  border: none;
  transition: all 0.3s;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}
</style>